import React, { useState } from 'react';
import { Card, Table, Button, Input, Form, Modal, Space, Tag, Tooltip, Popconfirm, Switch, ColorPicker, Select } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';

const { Option } = Select;

/**
 * 图谱节点类型管理组件
 * 用于管理和自定义图谱中的节点类型
 */
const GraphNodeTypeManager = ({ nodeTypes = [], onUpdate }) => {
  const [form] = Form.useForm();
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentNodeType, setCurrentNodeType] = useState(null);
  const [searchText, setSearchText] = useState('');

  // 表格列定义
  const columns = [
    {
      title: '节点类型名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <div 
            style={{ 
              width: 16, 
              height: 16, 
              borderRadius: '50%', 
              background: record.color || '#1677ff',
              display: 'inline-block',
              marginRight: 8
            }} 
          />
          <span>{text}</span>
          {record.isSystem && <Tag color="blue">系统</Tag>}
        </Space>
      ),
    },
    {
      title: '标识符',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '属性',
      dataIndex: 'properties',
      key: 'properties',
      render: (properties) => (
        <Space wrap>
          {properties && properties.map(prop => (
            <Tag key={prop.name}>{prop.name}</Tag>
          ))}
          {(!properties || properties.length === 0) && <span>无</span>}
        </Space>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
            disabled={record.isSystem}
          />
          <Popconfirm
            title="确定删除此节点类型吗？"
            description="删除后将无法恢复，已使用此类型的节点将变为未分类。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
            disabled={record.isSystem}
          >
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />} 
              disabled={record.isSystem}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理编辑
  const handleEdit = (record) => {
    setCurrentNodeType(record);
    form.setFieldsValue({
      name: record.name,
      identifier: record.identifier,
      description: record.description,
      color: record.color || '#1677ff',
      icon: record.icon,
      properties: record.properties || [],
    });
    setEditModalVisible(true);
  };

  // 处理删除
  const handleDelete = (record) => {
    const updatedTypes = nodeTypes.filter(item => item.identifier !== record.identifier);
    onUpdate?.(updatedTypes);
  };

  // 处理添加
  const handleAdd = () => {
    setCurrentNodeType(null);
    form.resetFields();
    form.setFieldsValue({
      color: '#1677ff',
      properties: [],
    });
    setEditModalVisible(true);
  };

  // 保存节点类型
  const handleSave = () => {
    form.validateFields().then(values => {
      let updatedTypes;
      
      if (currentNodeType) {
        // 编辑现有类型
        updatedTypes = nodeTypes.map(item => 
          item.identifier === currentNodeType.identifier ? { ...values, id: item.id } : item
        );
      } else {
        // 添加新类型
        const newNodeType = {
          ...values,
          id: `node_type_${Date.now()}`,
          isSystem: false,
        };
        updatedTypes = [...nodeTypes, newNodeType];
      }
      
      onUpdate?.(updatedTypes);
      setEditModalVisible(false);
    });
  };

  // 过滤节点类型
  const filteredNodeTypes = nodeTypes.filter(
    item => item.name.toLowerCase().includes(searchText.toLowerCase()) || 
           item.description.toLowerCase().includes(searchText.toLowerCase())
  );

  // 转换为表格数据
  const tableData = filteredNodeTypes.map(item => ({
    key: item.id,
    ...item,
  }));

  // 属性表单列表
  const [properties, setProperties] = useState([]);
  
  // 添加属性
  const handleAddProperty = () => {
    const newProperties = [...properties, { name: '', type: 'string', required: false }];
    setProperties(newProperties);
    form.setFieldsValue({ properties: newProperties });
  };
  
  // 删除属性
  const handleRemoveProperty = (index) => {
    const newProperties = properties.filter((_, i) => i !== index);
    setProperties(newProperties);
    form.setFieldsValue({ properties: newProperties });
  };

  return (
    <div>
      <Card 
        title="节点类型管理" 
        extra={
          <Space>
            <Input.Search
              placeholder="搜索节点类型..."
              allowClear
              onSearch={value => setSearchText(value)}
              style={{ width: 200 }}
            />
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAdd}
            >
              添加节点类型
            </Button>
          </Space>
        }
      >
        <Table 
          columns={columns} 
          dataSource={tableData} 
          pagination={{ pageSize: 10 }}
          size="middle"
        />
      </Card>

      <Modal
        title={currentNodeType ? "编辑节点类型" : "添加节点类型"}
        open={editModalVisible}
        onOk={handleSave}
        onCancel={() => setEditModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="节点类型名称"
            rules={[{ required: true, message: '请输入节点类型名称' }]}
          >
            <Input placeholder="例如：概念、实体、属性" />
          </Form.Item>
          
          <Form.Item
            name="identifier"
            label="标识符"
            rules={[{ required: true, message: '请输入标识符' }]}
            tooltip="用于系统内部标识此节点类型的唯一标识符，建议使用小写英文和下划线"
          >
            <Input placeholder="例如：concept、entity、attribute" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={3} placeholder="请描述此节点类型的含义和用途" />
          </Form.Item>
          
          <Form.Item
            name="color"
            label="颜色"
          >
            <ColorPicker />
          </Form.Item>
          
          <Form.Item
            name="icon"
            label="图标"
          >
            <Input placeholder="图标名称或URL" />
          </Form.Item>
          
          <div style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <span>属性定义</span>
              <Button type="link" onClick={handleAddProperty} icon={<PlusOutlined />}>
                添加属性
              </Button>
            </div>
            
            {properties.map((prop, index) => (
              <div key={index} style={{ display: 'flex', marginBottom: 8, gap: 8 }}>
                <Form.Item
                  name={['properties', index, 'name']}
                  style={{ flex: 1, marginBottom: 0 }}
                >
                  <Input placeholder="属性名称" />
                </Form.Item>
                <Form.Item
                  name={['properties', index, 'type']}
                  style={{ width: 120, marginBottom: 0 }}
                >
                  <Select>
                    <Option value="string">文本</Option>
                    <Option value="number">数字</Option>
                    <Option value="boolean">布尔值</Option>
                    <Option value="date">日期</Option>
                    <Option value="url">URL</Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name={['properties', index, 'required']}
                  valuePropName="checked"
                  style={{ width: 80, marginBottom: 0 }}
                >
                  <Switch checkedChildren="必填" unCheckedChildren="选填" />
                </Form.Item>
                <Button 
                  type="text" 
                  danger 
                  icon={<DeleteOutlined />} 
                  onClick={() => handleRemoveProperty(index)}
                />
              </div>
            ))}
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default GraphNodeTypeManager;